import os
import time
import allure

from allure_commons.types import AttachmentType
# from PIL import Image, ImageDraw, ImageFont
from tools.reader.config_reader import ConfigReader


def singleton(cls, *args, **kwargs):
    """
    Decorator, lazy singleton mode, initialized once and no longer initialized
    """
    instances = {}

    def _singleton():
        if cls not in instances:
            # Use decorators to control __call__ methods that are called
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return _singleton


def ui_exception_record(func):
    """
    This decorator catches exceptions during Selenium operations and takes a screenshot.
    """

    def inner(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            # 从传入的参数中获取第一个参数的 _driver 属性，并将其存储在变量 _driver 中
            driver = args[0]._driver
            now_time = time.strftime("%Y.%m.%d.%H.%M.%S")
            # 使用当前时间格式化为字符串，并将其存储在变量 now_time 中
            directory_path = ConfigReader().read("screenshot")["classpath"]
            is_exist = os.path.exists(directory_path)
            if not is_exist:
                os.makedirs(directory_path)
            file_name = "Error-{}.png".format(now_time)
            full_path = os.path.join(directory_path, file_name)
            driver.save_screenshot(full_path)
            # add_watermark(full_path)
            allure.attach.file(full_path, file_name, attachment_type=AttachmentType.PNG)
            raise e

    return inner


# def add_watermark(img_file):
#     # 打开图像文件
#     image = Image.open(img_file)
#     # 初始化绘图对象
#     draw = ImageDraw.Draw(image)
#     # 定义字体和颜色
#     myfont = ImageFont.truetype("C:\\windows\\fonts\\Arial.ttf", size=25)
#     fillcolor = '#ff0000'
#     # 获取时间戳并转换为字符串格式
#     timestr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
#     width, height = image.size
#     # 在图像上添加水印
#     draw.text((width - 270, height - 50), timestr, font=myfont, fill=fillcolor)
#     image.save(img_file)
